<template>
<div id="app-setting">
  <v-header class="pd-left15" title="应用设置" :showDownloadBtn = "download" :saveShow = "save"></v-header>
  <div class="container_wrap">
  <el-container class="container-box">
    <el-header height="50px" class="header-tool-bar">
      <!-- 按钮 -->
      <el-row class="toolbar">
        <el-col :span="12">
          <el-button type="primary" size="mini" @click="adddialogForm">增加</el-button>
          <el-button type="primary" size="mini" @click.stop="removedata">删除</el-button>
          <el-button type="primary" size="mini" @click="handleEdit">编辑</el-button>
          <el-button type="primary" size="mini" @click="refresh">刷新</el-button>
        </el-col>
      </el-row>
      </el-header>
    <!-- <el-header height="58px">
        <el-row class="toolbar">
          <el-button type="primary" size="mini" @click="addOrgBtnClick">增加</el-button>
          <el-button type="primary" size="mini" @click="delOrgBtnClick">删除</el-button>
          <el-button type="primary" size="mini" @click="editOrgBtnClick">编辑</el-button>
          <el-button type="primary" size="mini" @click="refreshOrgTreeData">刷新</el-button>
        </el-row>
      </el-header> -->
    <el-main class="main-table-box">
      <!-- 表单 -->
      <el-table ref="table" :data="tableData" @select="checkrow" v-loading="tableLoading"
        tooltip-effect="dark" style="width: 100%">
        <el-table-column type="selection" width="auto">
        </el-table-column>
        <el-table-column prop="app_name" label="应用名称" width="auto">
        </el-table-column>
        <el-table-column prop="app_id" label="应用ID" width="auto">
        </el-table-column>
        <!-- <el-table-column prop="app_type" label="应用类型" width="auto">
        </el-table-column> -->
        <el-table-column label="创建时间" width="auto">
          <template slot-scope="scope">
            {{scope.row.app_create_time | capitalize}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="edit(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="totalCount">
        </el-pagination>
    </el-main>
  </el-container>
  </div>
  <!-- 新增/编辑-弹窗 -->
    <el-dialog :title="addRoleDialogMode === 'ADD' ? '新增设置' : '编辑设置'"
               :visible.sync="addRoleDialogVisiable"
               @close="cancel"
               width="900px"
               >
      <el-form :model="ruleForm" :rules="rules"  ref="ruleForm" label-width="140px" class="demo-ruleForm">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item v-if="addRoleDialogMode === 'MODIFY'" label="应用ID" prop="app_id">
              <el-input v-model="ruleForm.app_id" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item v-else label="应用ID" prop="app_id">
              <el-input v-model="ruleForm.app_id"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用名称" prop="app_name">
              <el-input v-model="ruleForm.app_name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="应用类型" prop="app_type">
              <el-select v-model="ruleForm.app_type" placeholder="请选择" popper-class="zIndex-popper">
                <el-option
                  v-for="item in appType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
           <el-form-item label="创建时间" prop="app_create_time">
           <el-input v-model="ruleForm.app_create_time" ></el-input>
           </el-form-item>
          </el-col>
        </el-row> -->
        <el-form-item class="dialogbtn">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel('ruleForm')">关闭</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 设置弹框 -->
    <el-dialog title='选择系统' :visible.sync="selectSysVisiable" @close="sysCancel" width="900px">
      <el-table ref="sysTable" :data="sysTableData" @select="checkRowSys" @select-all="all" v-loading="tableLoading"
        tooltip-effect="dark" style="width: 100%">
        <el-table-column type="selection" width="auto">
        </el-table-column>
        <el-table-column prop="sys_name" label="系统名称" width="auto">
        </el-table-column>
        <el-table-column prop="sys_no" label="系统编号" width="auto">
        </el-table-column>
        <el-table-column prop="icon_id" label="logo" width="auto">
        </el-table-column>
        <el-table-column prop="sys_url" label="url地址" width="auto">
        </el-table-column>
      </el-table>
      <!-- <el-pagination
          @current-change="sysCurrentChange"
          :current-page="sysCurrentPage"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="sysTotalCount">
        </el-pagination> -->
      <el-row class="mg15">
        <el-button type="primary" @click="submitSys">确定</el-button>
        <el-button @click="sysCancel">关闭</el-button>
      </el-row>
    </el-dialog>
</div>
</template>

<script>
  import '../../../assets/css/mixinParameterManager.styl'
  // import { formatTransDate } from '../../../assets/js'
  // import Msg from '../../../assets/js/msg.js'
  import ajax from '../../../api/ajax/ajax'
  import {VHeader} from '../../../components'
  import api from '../../../api/url'
  // import {cnValidator} from '../../../assets/js/rules'
export default{
  name: 'system-list',
  components: {
    VHeader
  },
  data () {
      return {
        tableLoading: true,
        condition: '', // 输入条件
        addRoleDialogVisiable: false,
        selectSysVisiable: false,
        editdialogform: false,
        currentPage: 1, // 当前页码
        sysCurrentPage: 1,
        pagesize: 10, // 默认每页数据量
        totalCount: 0, // 默认数据总数
        sysTotalCount: 0,
        editmetaid: false, // meta_id input框禁止修改
        editsysid: false, // event_id input框禁止修改
        checked: false,
        checkedRow: [],
        sysIdARr: [],
        appId: '',
        tableData: [],
        sysTableData: [],
        checkbox: [],
        addRoleDialogMode: 'ADD', // 对话框色对话框模式  ADD新增 MODIFY 修改
        list: [],
        download: false,
        save: false,
        ruleForm: {
          app_name: '',
          app_id: '',
          app_type: '',
          app_create_time: ''
        },
        appType: [{
          value: 'android',
          label: 'android'
        }, {
          value: 'ios',
          label: 'ios'
        }],
        rules: {
          app_name: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          app_id: [
            { required: true, message: '请输入', trigger: 'blur' }
          ]
        },
        currentItem: {}
      }
    },
    created () {
      this.queryForPage()
    },
    filters: {
      // 这里先这样写，创建时间以后可能要做转换
      capitalize (val) {
        return val.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/g, '$1-$2-$3 $4:$5:$6')
      }
    },
    methods: {
      // 请求应用列表封装
      queryForPage (pageNo = 1, pageSize = 10) {
        ajax.post(api.SEARCH_APP_LIST, {pageNo: pageNo, pageSize: pageSize}).then(res => {
          this.tableLoading = false
          this.tableData = []
          this.tableData = res.data.list
          this.totalCount = res.data.total
          this.checked = false
        })
      },
      // 点击设置请求系统列表封装
      querySysList (appid, pageNo = 1, pageSize = 10) {
        ajax.post(api.GET_SYSTEM_LIST, {pageNo: pageNo, pageSize: pageSize, app_id: appid}).then(res => {
          this.sysTableData = res.data
          this.sysTableData.forEach((items, index) => {
            if (items.isSelected === '1') {
              this.$nextTick(() => {
                this.$refs.sysTable.toggleRowSelection(this.sysTableData[index], true)
              })
            }
          })
        })
      },
      // 当前页数
      handleCurrentChange (val) {
        this.currentPage = val
        this.queryForPage(val)
      },
      // 系统弹出框-当前页数
      // sysCurrentChange (val) {
      //   this.sysCurrentPage = val
      //   // this.querySysList(val)
      // },
      // 增加按钮
      adddialogForm () {
        this.ruleForm = {}
        // this.currentItem = {}
        // this.$refs.table.clearSelection() // 点击新增清除选中状态
        // this.checked = false
        this.addRoleDialogVisiable = true
        this.addRoleDialogMode = 'ADD'
        // this.editmetaid = false
        // this.editsysid = false
      },
      // 关闭
      cancel (formName) {
        this.$refs.ruleForm.clearValidate()
        this.ruleForm = {}
        // this.$refs.ruleForm.resetFields() // 移除校验 重置为初始状态
        this.addRoleDialogVisiable = false
        this.editdialogform = false
        // this.ruleForm = this.currentItem
        // this.checked = false
        // this.handleSizeChange()
      },
      // 选择系统弹框取消
      sysCancel () {
        this.selectSysVisiable = false
      },
         // 重置
      resetForm () {
        if (this.addRoleDialogMode === 'MODIFY') {
          this.ruleForm = {...this.currentItem}
        } else {
          this.ruleForm = {}
        }
        this.$refs.ruleForm.clearValidate()
      },
      // 删除数据
      removedata () {
        if (this.checkedRow.length > 0) {
          this.$confirm('是否删除该记录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let deletAppId = this.checkedRow.map(item => {
              return item.app_id
            })
            ajax.post(api.DETELE_APP, deletAppId).then((res) => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.queryForPage(this.currentPage)
            })
          }).catch(() => {
          })
        } else {
          this.$message.error('请至少选择一条记录进行删除')
        }
      },
      checkrow (row) {
        this.checkedRow = row
        if (row.length > 0) {
          this.ruleForm = row[0]
          this.checkbox = row
          this.checked = true
        } else {
          this.checked = false
        }
      },
      all (selection) {
        this.sysIdARr = selection.map(items => {
          return items.sys_no
        })
        // this.sysIdARr = selecttion
      },
      // 编辑
      handleEdit () {
        // 判断是否勾选
        if (this.checked === true) {
          if (this.checkedRow.length < 2) {
            this.addRoleDialogVisiable = true // 显示弹框
            this.addRoleDialogMode = 'MODIFY' // 新增角色对话框模式 编辑模式
            this.ruleForm = JSON.parse(JSON.stringify(this.checkedRow[0]))
            this.currentItem = JSON.parse(JSON.stringify(this.ruleForm))
            // this.ruleForm = this.currentItem
          } else {
            this.$message.error('只能选择一条')
          }
        } else {
          this.$message.error('请至少选择一条记录进行编辑')
        }
      },
      // 设置
      edit (row) {
        this.appId = row.app_id
        this.selectSysVisiable = true
        this.querySysList(row.app_id)
      },
      // 系统设置选择
      // selectionChangeSys () {},
      checkRowSys (val) {
        let sysIdARr = val.map(item => {
          return item.sys_no
        })
        this.sysIdARr = sysIdARr
      },
      // 刷新
      refresh () {
        this.queryForPage(this.currentPage)
      },
      // 新增/修改 元事件
      submitForm () {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
              // 新增接口
            if (this.addRoleDialogMode === 'ADD') {
              ajax.post(api.ADD_APP, this.ruleForm).then(res => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.queryForPage(this.currentPage)
              })
            } else {
              ajax.post(api.REFRESH_APP, this.ruleForm).then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.queryForPage()
              })
            }
            this.addRoleDialogVisiable = false
        } else {
          return false
        }
      })
    },
    // 选系统提交
    submitSys () {
      let postData = {
        sys_no: this.sysIdARr,
        app_id: this.appId
      }
      ajax.post(api.APP_ADD_SYS, postData).then(res => {
        this.$message({
          type: 'success',
          message: '增加成功'
        })
        this.sysCancel()
      }).catch(error => {
        console.info(error)
      })
    }
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus">
  #app-setting
    .pd-left15
      padding-left 15px
    .el-select
      width 100%
    .mg15
      margin 15px 0
    .container-box
      .header-tool-bar
        padding-left 15px
        line-height 50px
</style>
